<?php
declare(strict_types=1);
namespace Service\CommodityAttributeService;

use App\Model\CommodityModel\Countryinfo;
use App\Model\CommodityModel\Unit;
use App\Model\CommodityModel\Brandinfo;
use App\Model\CommodityModel\CustomCountryInfo;
use App\Model\CommodityModel\CustomCurrency;
use App\Model\CommodityModel\CustomUnitInfo;
use Service\BaseService;

class CommodityAttributeBaseService extends BaseService
{
    /**
     * 获取商品属性Id
     * @param $redisKey
     * @param $attributeClass
     * @param $attributeName
     * @param $dataName
     * @return int|mixed
     * @throws \RedisException
     */
    public function getIdByName($redisKey, $attributeClass, $attributeName,$dataName)
    {
        if (empty($dataName)){
            return 0;
        }

        $redis = $this->getRedisObj();
        $dataMapJson = $redis->get($redisKey);

        if (!$dataMapJson) {

            $data = $attributeClass::instance()
                ->select(
                    ['CONCAT(ID,"") AS ID', $attributeName]
                )
                ->get()->toArray();
            $dataMap = array_column($data, 'ID', $attributeName);
            //保存到redis
            $redis->set($redisKey, json_encode($dataMap));

        } else {

            $dataMap = json_decode($dataMapJson, true);
        }
        //匹配数据
        if (isset($dataMap[$dataName])) {
            return $dataMap[$dataName];
        }
        return 0;
    }



    public function getCustomIdByName($redisKey, $attributeClass, $attributeKey,$attributeName,$dataName)
    {

        if (empty($dataName)){
            return 0;
        }

        $redis = $this->getRedisObj();
        $dataMapJson = $redis->get($redisKey);

        if (!$dataMapJson) {

            $data = $attributeClass::instance()
                ->select(
                    [$attributeKey, $attributeName]
                )
                ->get()->toArray();
            $dataMap = array_column($data, $attributeKey, $attributeName);
            //保存到redis
            $redis->set($redisKey, json_encode($dataMap));

        } else {

            $dataMap = json_decode($dataMapJson, true);
        }
        //匹配数据
        if (isset($dataMap[$dataName])) {

            return $dataMap[$dataName];

        }
        return 0;
    }

}